package com.buddy.summary.code.algorithm;

public class LinkedList {
    private static class Node{
        int data;
        Node next;

        Node(int data) {
            this.data = data;
        }
    }

    private Node head;
    private Node last;
    private int size;

    private void insert(int data,int index){
        if (index < 0 || index > size){
            throw new IndexOutOfBoundsException("超出链表节点范围");
        }
        Node insertedNode = new Node(data);
        if (size == 0){
            //空链表
            head = insertedNode;
            last = insertedNode;
        }else if (index == 0){
            //头部插入
            insertedNode.next = head;
            head = insertedNode;
        }else if (size == index){
            //尾部插入
            last.next = insertedNode;
            last = insertedNode;
        }else{
            //中间插入
            Node prevNode = get(index -1);
            insertedNode.next = prevNode.next;
            prevNode.next = insertedNode;
        }
        size++;
    }

    private Node remove(int index){
        if (index < 0 || index > size){
            throw new IndexOutOfBoundsException("超出链表范围");
        }
        Node removeNode = null;
        if (index == 0){
            //删除头节点
            removeNode = head;
            head = head.next;
        }else if (index == size - 1){
            //删除尾部节点
            Node prevNode = get(index - 1);
            removeNode = prevNode.next;
            prevNode.next = null;
            last = prevNode;
        }else{
            //删除中间节点
            Node prevNode = get(index - 1);
            Node nextNode = prevNode.next.next;
            removeNode = prevNode.next;
            prevNode.next = nextNode;
        }
        size --;
        return removeNode;
    }

    private Node get(int index) {
        if (index < 0 || index > size){
            throw new IndexOutOfBoundsException("超出链表范围");
        }
        Node temp = head;
        for (int i=0;i<index;i++){
            temp = temp.next;
        }
        return temp;
    }

    private void output(){
        Node temp = head;
        while (temp != null ){
            System.out.println(temp.data);
            temp = temp.next;
        }
    }

    public static void main(String[] args) {
        LinkedList linkedList = new LinkedList();
        for (int i=0;i<10;i++){
            linkedList.insert(i,i);
        }
        linkedList.remove(0);
        linkedList.output();
    }

}
